package start.spring.basic.util.common;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import lombok.extern.slf4j.Slf4j;

/**
 * ****************************************************************************
 * 数据库操作工具类
 *
 * @author(作者)：xuyongyun	
 * @author(复审人)：	Administrator 2018年8月22日
 * @version(版本)1.0
 * @since 1.0
 ******************************************************************************
 */
@Slf4j
public class DBUtil {
	
	public static Connection getConnection(DataSource ds) throws SQLException {
		log.debug("Get Connection !");
		Connection conn = null;
		if(ds!=null) {
			conn = ds.getConnection();
		}
		return conn;
	}

	/**
	 * 关闭连接
	 * 
	 * @param conn
	 * 
	 * @param conn
	 * @throws SQLException 
	 * @since 1.0
	 */
	public static void closeConnection(Connection conn) {
		log.debug("Close connection !");
		try {
			if (conn != null) {
				conn.close();
				conn = null;
			}
		}catch(Exception e) {
			log.error("Close Statement error!",e);
		}
		
	}

	/**
	 * 关闭Statement
	 * 
	 * @param stmt
	 * 
	 * @param stmt
	 * @throws SQLException 
	 * @since 1.0
	 */
	public static void closeStatement(Statement stmt) {
		log.debug("Close Statement !");
		try {
			if (stmt != null) {
				stmt.close();
				stmt = null;
			}
		}catch(Exception e) {
			log.error("Close Statement error!",e);
		}
	}

	/**
	 * 关闭PreparedStatement
	 * 
	 * @param stmt
	 * 
	 * @param stmt
	 * @throws SQLException 
	 * @since 1.0
	 */
	public static void closePreparedStatement(PreparedStatement pstmt) {
		log.debug("Close PreparedStatement !");
		try {
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		}catch(Exception e) {
			log.error("Close PreparedStatement error!",e);
		}
	}

	/**
	 * 关闭ResultSet
	 * 
	 * @param rs
	 * 
	 * @param rs
	 * @throws SQLException 
	 * @since 1.0
	 */
	public static void closeResultSet(ResultSet rs) {
		log.debug("Close ResultSet!");
		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
		}catch(Exception e) {
			log.error("Close ResultSet error!",e);
		}
	}
	
	/**
	 * 回滚事务
	 * 
	 * @param conn
	 * @throws SQLException 
	 * 
	 * @since 1.0
	 */
	public static void rollBack(Connection conn) {
		log.debug("rollBack!");
		try {
			if (conn != null) {
				conn.rollback();
			}
		}catch(Exception e) {
			log.error("conn roll back error!",e);
		}
	}
	
	/**
	 * 设置事务是否自动提交
	 *	
	 * @param conn 连接
	 * @param autoCommit 是否自动提交，true自动提交，false不自动提交
	 * @throws SQLException 
	 * @since           1.0
	 */
	public static void setAutoCommit(Connection conn,boolean autoCommit) {
		log.debug("setAutoCommit!");
		try {
			if (conn != null) {
				conn.setAutoCommit(autoCommit);
			}
		}catch(Exception e) {
			log.error("set auto commit error!",e);
		}
	}
}
